import { getQueryString } from "./Utils";

/** 去掉微信授权的code参数 */
function deleteCodeQuery(url: string): string {
  const newUrl = url.replace(/(^|&)code=([^&]*)(&|$)/, "&");
  return newUrl.endsWith("&") ? newUrl.substring(0, newUrl.length - 1) : newUrl;
}

/**
 * 处理url 去掉微信返回时带的参数
 */
export function handleWXbackUrl() {
  const w = location.href.indexOf("?");
  const j = location.href.indexOf("#");
  let href = window.location.href;
  let url;
  if (w !== -1 && j > w) {
    href =
      location.href.substr(0, w) +
      location.href.substr(j, location.href.length);
    url = href;
  } else {
    url = location.href;
  }
  return url;
}

/**
 * 微信授权
 * @param weChatAppId weChatAppId
 */
export function auth(weChatAppId: string) {
  const callbackUrl = handleWXbackUrl();
  const url = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${weChatAppId}&redirect_uri=${encodeURIComponent(
    callbackUrl
  )}&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect`;
  const result = getQueryString();
  if (result.get("code") && !sessionStorage.getItem("flag")) {
    return result.get("code");
  } else {
    sessionStorage.removeItem("flag");
    window.location.replace(deleteCodeQuery(url));
  }
}
